package com.example.widgethost.base;

import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;

import java.util.List;

public abstract class BaseContainerConstructor<T extends ViewGroup, S extends ViewGroup.LayoutParams, K extends AppWidgetHost> extends AbstractContainerConstructor<T, S, K> {
    private static final String TAG = "BaseContainerConstructor";

    /**
     * constructor.
     *
     * @param context
     * @param t
     */
    public BaseContainerConstructor(Context context, T t) {
        super(context, t);
    }

    /**
     * get target provider info.
     *
     * @return target provider info array
     */
    protected abstract String[] getTargetProviderInfo();

    /**
     * add default widgets to host.
     */
    public final void addDefaultWidgetsToHost() {
        List<AppWidgetProviderInfo> appWidgetProviderInfos = getAllProvider();
        String[] targetProviderInfos = getTargetProviderInfo();
        for (String strTargetProviderInfo : targetProviderInfos) {
            String[] targetProviderInfoArray = strTargetProviderInfo.split(Config.TARGET_PROVIDER_INFO_SEPARATOR);
            ComponentName targetComponentName = ComponentName.createRelative(targetProviderInfoArray[0], targetProviderInfoArray[1]);
            AppWidgetProviderInfo appWidgetProviderInfo = null;
            for (AppWidgetProviderInfo tempAppWidgetProviderInfo : appWidgetProviderInfos) {
                ComponentName componentName = tempAppWidgetProviderInfo.provider;
                if (targetComponentName.equals(componentName)) {
                    appWidgetProviderInfo = tempAppWidgetProviderInfo;
                    break;
                }
            }
            if (appWidgetProviderInfo != null) {
                addWidget(appWidgetProviderInfo);
            }
        }

    }

    /**
     * get all installed provider.
     *
     * @return installed provider list
     */
    private List<AppWidgetProviderInfo> getAllProvider() {
        List<AppWidgetProviderInfo> appWidgetProviderInfos = appWidgetManager.getInstalledProviders();
        for (AppWidgetProviderInfo appWidgetProviderInfo : appWidgetProviderInfos) {
            Log.d(TAG, appWidgetProviderInfo.provider.getClassName() + "//" + appWidgetProviderInfo.provider.getPackageName());
        }
        return appWidgetProviderInfos;
    }
}
